package com.liyongjian.xhban.api;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.liyongjian.xhban.dal.AccountGroupDetailRepository;
import com.liyongjian.xhban.dal.AccountGroupRepository;
import com.liyongjian.xhban.dal.UserFriendConfirmRepository;
import com.liyongjian.xhban.dal.UserFriendRepository;
import com.liyongjian.xhban.dal.UserMsgRepository;
import com.liyongjian.xhban.dal.UserRepository;
import com.liyongjian.xhban.dto.AjaxResponse;
import com.liyongjian.xhban.dto.SessionUser;
import com.liyongjian.xhban.exception.XHBanException;
import com.liyongjian.xhban.model.AccountGroupDetail;
import com.liyongjian.xhban.model.User;
import com.liyongjian.xhban.model.UserFriend;
import com.liyongjian.xhban.model.UserFriendConfirm;
import com.liyongjian.xhban.model.UserMsg;
import com.liyongjian.xhban.model.emumm.MsgType;
import com.liyongjian.xhban.model.emumm.VerifyState;
import com.liyongjian.xhban.utils.MapUtils;


@Controller
@RequestMapping("/api/msg")
public class MsgController extends BaseController {
    @Autowired
    private UserFriendRepository userFriendRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserFriendConfirmRepository userFriendConfirmRepository;
    @Autowired
    private UserMsgRepository userMsgRepository;
    @Autowired
    private AccountGroupDetailRepository accountGroupDetailRepository;
    @Autowired
    private AccountGroupRepository accountGroupRepository;

    @ResponseBody
    @RequestMapping(path = "my/list", method = RequestMethod.GET)
    public AjaxResponse my_list(HttpServletRequest request, String token,
            HttpServletResponse response,
            @PageableDefault(sort = {"id"}, direction = Direction.DESC) Pageable pageable)
                    throws Exception {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getCurrentUser(token);
        Page<UserMsg> page = userMsgRepository.findFriendByLookUserId(su.id, pageable);
        return ajax.setObj(page.map(new Converter<UserMsg, Map<String, Object>>() {
            public Map<String, Object> convert(UserMsg source) {
                Map<String, Object> map = MapUtils.convert(source);
                User user = userRepository.findOne(source.userId);
                map.put("photo", user.photo);
                map.put("nickName", user.nickName);
                if (source.type == MsgType.HY) {
                    UserFriendConfirm ufc = userFriendConfirmRepository.findByUserMsgId(source.id);
                    map.put("ufcState", ufc.state);
                } else if (source.type == MsgType.JZ) {
                    AccountGroupDetail agd =
                            accountGroupDetailRepository.findByUserMsgId(source.id);
                    map.put("agdState", agd.state);
                    map.put("blogId", agd.blogId);
                }
                return map;
            }
        }));
    }



    @Transactional
    @ResponseBody
    @RequestMapping(path = "verify", method = RequestMethod.POST)
    public AjaxResponse add(HttpServletRequest request, String token, Long id, VerifyState state,
            HttpServletResponse response) throws Exception {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getCurrentUser(token);
        UserMsg um = userMsgRepository.findOne(id);
        if (um.lookUserId != su.id) {
            throw new XHBanException("没有权限");
        }
        if (um.type == MsgType.HY) {
            UserFriendConfirm ufc = userFriendConfirmRepository.findByUserMsgId(um.id);
            ufc.state = state;
            userFriendConfirmRepository.save(ufc);

            UserFriend uff =
                    userFriendRepository.findByUserIdAndFriendUserId(ufc.userId, ufc.friendUserId);
            if (uff == null) {
                if (state == VerifyState.TG) {
                    UserFriend uf = new UserFriend();
                    uf.userId = ufc.userId;
                    uf.friendUserId = ufc.friendUserId;
                    userFriendRepository.save(uf);

                    UserFriend uf2 = new UserFriend();
                    uf2.userId = ufc.friendUserId;
                    uf2.friendUserId = ufc.userId;
                    userFriendRepository.save(uf2);
                }
            }


        } else if (um.type == MsgType.JZ) {
            AccountGroupDetail agd = accountGroupDetailRepository.findByUserMsgId(um.id);
            agd.state = state;
            accountGroupDetailRepository.save(agd);

            if (state == VerifyState.TG) {
                accountGroupRepository.updatePayMoneyByUserIdAndGroupId(agd.userId, agd.groupId,
                        agd.money);
                String[] ids = StringUtils.strip(agd.userIds, ",").split(",");
                for (String userId : ids) {
                    if (!StringUtils.isEmpty(userId)) {
                        accountGroupRepository.updateMoneyByUserIdAndGroupId(Long.valueOf(userId),
                                agd.groupId, agd.userIdsMoney);
                    }
                }
            } else {
                UserMsg um2 = new UserMsg();
                um2.type = MsgType.XX;
                um2.userId = um.lookUserId;
                um2.lookUserId = um.userId;
                um2.text = "你的入账请求没有通过";
                userMsgRepository.save(um2);
            }
        }
        return ajax;
    }



    @Transactional
    @ResponseBody
    @RequestMapping(path = "verify_hh", method = RequestMethod.POST)
    public AjaxResponse verify_hh(HttpServletRequest request, String token, Long id,
            VerifyState state, HttpServletResponse response) throws Exception {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getCurrentUser(token);

        AccountGroupDetail agd = accountGroupDetailRepository.findOne(id);
        agd.state = state;
        accountGroupDetailRepository.save(agd);
        if (state == VerifyState.TG) {
            accountGroupRepository.updatePayMoneyByUserIdAndGroupId(agd.userId, agd.groupId,
                    agd.money);
            String[] ids = StringUtils.strip(agd.userIds, ",").split(",");
            for (String userId : ids) {
                if (!StringUtils.isEmpty(userId)) {
                    accountGroupRepository.updateMoneyByUserIdAndGroupId(Long.valueOf(userId),
                            agd.groupId, agd.userIdsMoney);
                }
            }
        } else {
        }
        return ajax;
    }

}
